#!/usr/bin/python2.7
# All rights to this package are hereby disclaimed and its contents
# released into the public domain by the authors.
'''This script helps setup the AppEngine directory.

Usage (must be run inside the ch12 folder):
  python setup_appengine.py \
    <App Engine app id> \
    <BQ project id> \
    <GCS bucket>

Note: the AppEngine service account must have write access
to the BQ project and GCS bucket.
'''

import os
import sys
import zipfile

def main(app_id, project, bucket):
  # Generate configs.
  config = {
    'app_id': app_id,
    'project': project,
    'bucket': bucket
  }
  for filename, template in _TEMPLATES:
    with open(os.path.join('appengine', filename), 'w') as config_file:
      config_file.write('# Auto-generated by setup_appengine.py\n')
      config_file.write(template % config)
  # Add dependencies.
  with zipfile.ZipFile('appengine_deps.zip', 'r') as deps:
    deps.extractall('appengine')

_TEMPLATES = [
  ('controller.yaml',
   '''
application: %(app_id)s
module: controller
version: 1
runtime: python27
api_version: 1
threadsafe: yes
instance_class: B4
basic_scaling:
  max_instances: 1

handlers:
- url: /mapreduce/pipeline/images
  static_dir: mapreduce/lib/pipeline/ui/images

- url: /mapreduce(/.*)?
  script: mapreduce.main.APP
  login: admin

- url: .*
  script: controller.app
  login: admin

libraries:
- name: webapp2
  version: latest
- name: pycrypto
  version: latest

skip_files:
- ^(.*/)?#.*#
- ^(.*/)?.*~
- ^(.*/)?.*\.py[co]
- ^(.*/)?.*/RCS/.*
- ^(.*/)?\..*
'''
  ),
  ('config.py',
   '''
PROJECT_ID = "%(project)s"
GCS_BUCKET = "%(bucket)s"
'''
  )]

if __name__ == "__main__":
  if len(sys.argv) != 4:
    print __doc__
  else:
    main(*sys.argv[1:])
